﻿using System;
using Icms.Core.Model;
using Icms.Core.Repository;
using Icms.WebUI.Dto;
using Omu.ValueInjecter;

namespace Icms.WebUI.Builder
{
    public class GuidToParameterTitle<T> : ConventionInjection where T : ITitle
    {
        private readonly IRepo<T> _repo;

        public GuidToParameterTitle(IRepo<T> repo)
        {
            _repo = repo;
        }

        protected override bool Match(ConventionInfo c)
        {
            return c.SourceProp.Name == c.TargetProp.Name
                && (c.SourceProp.Type == typeof(Guid) || c.SourceProp.Type == typeof(Guid?)) &&
                   c.TargetProp.Type == typeof(string) && c.SourceProp.Value != null && c.TargetProp.Value == null;
        }

        protected override object SetValue(ConventionInfo c)
        {

            var o = _repo.Get((Guid) c.SourceProp.Value);
            if(o!=null)
                return o.Title;
            return null;
        }
    }
}